<?php
namespace app\api\controller;

use \think\Controller;
use \think\Db;
class Apilogin extends Base
{
    /**
     * 手机号验证登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public function userLogin(){
        if(!isset($_POST['phone'])){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        if(preg_match("/^1[123456789]\d{9}$/", $phone)){
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
            if(empty($username)){
                $today = date('Y-m-d H:i:s');
                $insert = [
                    'user_username' => '用户' . substr($phone,7,4),
                    'user_image' => '',
                    'user_phone' => $phone,
                    'user_time' => $today,
                    'user_updatetime' => $today,
                ];
                Db::table('up_u_user')->insert($insert);
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
            }
            if($username['user_status'] == 2){
                return json(['status' => 4, 'msg' => "此账户已被冻结！"]);
            }
            if($username['user_status'] == 3){
                return json(['status' => 4, 'msg' => "此账户已注销！"]);
            }
            if($username['user_status'] != 1){
                return json(['status'=>4,'msg'=>'此账户已被冻结或注销']);
            }
            //更新token
            $token = md5(date('YmdHis') . rand(100000,999999));
            Db::table('up_u_user')->where('user_phone',$phone)
                ->update([
                    'user_token' => $token ,
                    'user_logintime' => date('Y-m-d H:i:s')
                ]);
            $username['user_token'] = $token;
            return json(['status'=>200,'msg'=>$username]);
        }else{
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }
 /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public function userLogin2(){
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[123456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json(['status'=>3,'msg'=>'没有此用户']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        if($username['user_status'] == 2){
                            return json(['status' => 4, 'msg' => "此账户已被冻结！"]);
                        }
                        if($username['user_status'] == 3){
                            return json(['status' => 4, 'msg' => "此账户已注销！"]);
                        }
                        if($username['user_status'] != 1){
                            return json(['status'=>4,'msg'=>'此账户已被冻结或注销']);
                        }
                        //更新token
                        $token = md5(date('YmdHis') . rand(100000,999999));
                        Db::table('up_u_user')->where('user_phone',$phone)
                            ->update([
                                'user_token' => $token ,
                                'user_logintime' => date('Y-m-d H:i:s')
                            ]);
                        $username['user_token'] = $token;
                        return json(['status'=>200,'msg'=>$username]);
                    }
                }
            }
        }else{
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是快捷登录和更换手机号(第一步) 2是注册和更换手机号(第二步) 3是忘记密码  4是第三方登录时的绑定手机号)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public function getPhoneCode(){
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            $today = date('Y-m-d H:i:s');
            $insert = [
                'user_image' => '',
                'user_phone' => $phone,
                'user_time' => $today,
                'user_updatetime' => $today,
            ];
            $about_content1 = Db::table('up_about')->where('id',19)->value('content');
            $about_content2 = Db::table('up_about')->where('id',20)->value('content');
            if($about_content1 == 1) $insert['user_d_auth_uids'] = '';
            if($about_content1 == 2) $insert['user_d_auth_uids'] = -1;
            if($about_content2 == 1) $insert['user_d_auth_sids'] = '';
            if($about_content2 == 2) $insert['user_d_auth_sids'] = -1;
            Db::table('up_u_user')->insert($insert);
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        }
        if(empty($username) && $type==1){
            return json(['status'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(empty($username) && $type==3){
            return json(['status'=>21,'msg'=>'没有此手机号码用户']);
        }
        if($username && $type==2){
            return json(['status'=>22,'msg'=>'已经有此手机号码用户']);
        }
        if($username && $type == 4) { //第三方登录时绑定手机号
            if($_POST['bind_type'] == 1) {
                $field = '_wx_';
            }else if($_POST['bind_type'] == 2) {
                $field = '_qq_';
            }else if($_POST['bind_type'] == 3) {
                $field = '_wb_';
            }else {
                $field = '_ios_';
            }
            if($username["user{$field}token"]) {
                return json(['status' => 0, 'msg' => '此号码已被绑定']);
            }
        }
        $num = GetRandCode();//6位数验证码
//        $num = 123456;//6位数验证码
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid,$num,$phone,'');//发送验证码
//        $sendres = [
//            'code' => '000000','msg' => 'error!'
//        ];
        if($sendres['code'] != '000000') {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json(['status' => 200, 'msg' => md5($num)]);
        }
    }
    /**
     * 手机号码登录
     * @return bool
     * 参数：phone，code
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4成功
     */

    public function phoneLogin(){
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $user_image = input('avatarUrl');
        $user_username = input('nickName');
        $user_login_type = input('user_type');
		if(!isset($user_login_type) || !$user_login_type) $user_login_type = 4;
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
		if($phone != '18013931555' && $phone != '15895980214'){
			 //=============================================
			$res = Db::table('up_phonecode')->where('phone',$phone)->find();
			//=============================================================
			if($code != $res['code']){
				return json(['status'=>21,'msg'=>'验证码错误']);
			}
			if($res['status'] == 1){
				return json(['status'=>21,'msg'=>'验证码已使用']);
			}
			$now = time();
			if($now - $res['time2'] >= 301){
				return json(['status'=>22,'msg'=>'验证码超时']);
			}
		}
       
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            $today = date('Y-m-d H:i:s');
            $insert = [
                'user_image' => '',
                'user_phone' => $phone,
                'user_login_type' => $user_login_type,
                'user_time' => $today,
                'user_updatetime' => $today,
            ];
            $about_content1 = Db::table('up_about')->where('id',19)->value('content');
            $about_content2 = Db::table('up_about')->where('id',20)->value('content');
            if($about_content1 == 1) $insert['user_d_auth_uids'] = '';
            if($about_content1 == 2) $insert['user_d_auth_uids'] = -1;
            if($about_content2 == 1) $insert['user_d_auth_sids'] = '';
            if($about_content2 == 2) $insert['user_d_auth_sids'] = -1;
            if($user_image) $insert['user_image'] = $user_image;
            if($user_username) $insert['user_username'] = $user_username;
            Db::table('up_u_user')->insert($insert);
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        }else{
            $insert = [
                'user_login_type' => $user_login_type,
                'user_updatetime' => date('Y-m-d H:i:s')
            ];
            if($user_image && !$username['user_image']) $insert['user_image'] = $user_image;
            if($user_username && !$username['user_username']) $insert['user_username'] = $user_username;
            Db::table('up_u_user')->where('user_phone',$phone)->update($insert);
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        }
        if(empty($username)){
            return json(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        if($username['user_status'] == 2){
            return json(['status' => 4, 'msg' => "此账户已被冻结！"]);
        }
        if($username['user_status'] == 3){
            return json(['status' => 4, 'msg' => "此账户已注销！"]);
        }
        if($username['user_status'] != 1){
            return json(['status'=>4,'msg'=>'此账户已被冻结或注销']);
        }
        Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
        $token = md5(date('YmdHis') . rand(100000,999999));
        Db::table('up_u_user')->where('user_phone',$phone)
            ->update([
                'user_token' => $token ,
                'user_logintime' => date('Y-m-d H:i:s')
            ]);
        $username['user_token'] = $token;
        return json(['status'=>200,'msg'=>$username]);
    }

    /**
     * 忘记密码
     * @return bool
     * phone  手机号
     * code  验证码
     */
    public function forgetPass()
    {
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $password = input('password');
        $password2 = input('password2');
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        if($password != $password2){
            return json(['status'=>1,'msg'=>'密码输入不一致']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }

        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }

        if($userInfo['user_status'] != 1) {
            return json(['status' => 0, ' msg' => '该账号已被冻结']);
        }
        //----------------------------------------------------------------------------
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            'user_token' => $token,
            'user_password' => md5($password)
        ];
        $res = Db::table('up_u_user')
            ->where('user_phone', $phone)
            ->update($update);
        if($res){
            Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
            $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $username]);
        }else{
            return json(['status' => 0, 'msg' => '修改密码失败']);
        }
    }
//-----------------------------------------------------------------------------------------------------------

    /**
     * 登陆后修改密码
     * @return \think\response\Json
     * new_password  新密码
     * verify_password  确认密码
     * user_id  用户ID
     */
    public function changePassword(){
        $new_password = trim(input('new_password'), ' ');
        $verify_password = trim(input('verify_password'), ' ');
        $user_id = input('user_id');

        if($new_password == ''){
            return json(['status' => 0, 'msg' => '请填写新密码']);
        }
        if($verify_password == ''){
            return json(['status' => 0, 'msg' => '请填写确认密码']);
        }
        if($new_password != $verify_password){
            return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
        }

        $update['user_password'] = md5($new_password);
        $update['user_updatetime'] = date('Y-m-d H:i:s');
        $res = Db::name('u_user')->where('user_id', $user_id)->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '修改失败']);
        }
    }


}